﻿namespace A12_Ex01_4
{
    public class Program
    {
        private const int k_StringLength = 9;

        public static void Main() 
        {
            System.Console.WriteLine("Enter a string with " + k_StringLength.ToString() + ". If you use 9 0's and 1's you'll get a treat:");
            string inputString = System.Console.ReadLine();

            bool isBinaryNumber = isBinary(inputString);
            bool isCorrectLength = inputString.Length == k_StringLength;

            if (isBinaryNumber)
            {
                System.Console.WriteLine("1. " + inputString + " is a binary number.");
            }

            if (isCorrectLength)
            {
                System.Console.WriteLine("2. " + inputString + " is of length " + inputString.Length.ToString() + "."); 
            }

            if (isBinaryNumber && isCorrectLength)
            {
                int numberInDecimal = convertToDecimal(inputString);
                System.Console.WriteLine("3. " + inputString + " in decimal is " + numberInDecimal.ToString() + ".");
                System.Console.Write("4. " + inputString);
                if (isPrimeNumber(numberInDecimal))
                {
                    System.Console.WriteLine(" is prime.");
                }
                else
                {
                    System.Console.WriteLine(" isn't prime.");
                }
            }
        }

        private static bool isBinary(string i_InputString)
        {
            bool isBin = true;

            for (int i = 0; i < i_InputString.Length; i++)
            {
                isBin = isBin && (i_InputString[i] == '0' || i_InputString[i] == '1');
            }

            return isBin;
        }

        private static int convertToDecimal(string i_BinaryString)
        {
            int decimalValue = 0;
            int weightOfDigit = 1;

            for (int i = i_BinaryString.Length - 1; i >= 0; i--)
            {
                decimalValue += weightOfDigit * (i_BinaryString[i] - '0');
                weightOfDigit *= 2;                
            }

            return decimalValue;
        }

        private static bool isPrimeNumber(int i_InputNumber)
        { 
            int rootOfInputNumber = (int)System.Math.Sqrt(i_InputNumber) + 1;
            int i = 2;
            bool isPrime = true;

            while (isPrime && (i <= rootOfInputNumber))
            {
                isPrime = isPrime && (i_InputNumber % i != 0);
                i++;
            }

            return isPrime;            
        }
    }
}
